package com.clear.prototype.deepwcopy.recursionclone;

import java.io.*;

public class DeepProtoType implements Serializable, Cloneable {
    public String name;
    public DeepCloneableTarget deepCloneableTarget;  // 引用类型

    public DeepProtoType() {
    }

    //  ===============深拷贝实现一：递归克隆：使用 clone()方法=======================
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        // 完成对基本数据类型（属性）和String 的克隆
        deep = super.clone();

        // 对引用类型的属性进行单独处理（即调用它们的clone方法）
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();

        return deepProtoType;
    }


    //  =======================深拷贝实现二：通过序列化方式（推荐使用）==================
    // todo 仅仅是为了进行深拷贝，忽略了流的关闭
    public Object deepClone() throws Exception{
        // 序列化
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);  // 当前整个对象以对象流的方式输出

        byte[] byteArray = bos.toByteArray();
        // 反序列化
        ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
        ObjectInputStream ois = new ObjectInputStream(bis);
        DeepProtoType copyObj = (DeepProtoType) ois.readObject();
        return copyObj;
    }
}